<script setup>
import { ref, computed, watch } from 'vue'

const props = defineProps({
  currentPage: {
    type: String,
    required: true
  }
})

const emit = defineEmits(['file-selected'])

const fileInput = ref(null)
const isLoading = ref(false)
const errorMessage = ref('')
const fileType = ref('image') // Default file type: 'image' or 'audio' or 'document'

// 根据当前页面计算可用的文件类型选项
const availableFileTypes = computed(() => {
  // 如果是知识问答页面，只允许文档类型
  if (props.currentPage === 'knowledge') {
    return ['document']
  }
  // 如果是会议记录页面，允许文档和音频类型
  if (props.currentPage === 'meeting') {
    return ['document', 'audio']
  }
  // 其他页面允许图片和音频
  return ['image', 'audio']
})

// 确保当前选择的文件类型在可用选项中
const ensureValidFileType = () => {
  if (!availableFileTypes.value.includes(fileType.value)) {
    fileType.value = availableFileTypes.value[0]
  }
}

// 在组件初始化和props变化时检查文件类型
ensureValidFileType()

// 监听props变化
watch(() => props.currentPage, () => {
  ensureValidFileType()
})

// 计算文件接受类型
const acceptTypes = computed(() => {
  switch (fileType.value) {
    case 'image':
      return 'image/*'
    case 'audio':
      return 'audio/*'
    case 'document':
      return '.pdf,.txt,.docx'
    default:
      return '*/*'
  }
})

// Handle file selection
const handleFileSelect = async (event) => {
  const file = event.target.files[0]
  if (!file) return
  
  try {
    isLoading.value = true
    errorMessage.value = ''
    
    // Validate file type
    if (fileType.value === 'image' && !file.type.startsWith('image/')) {
      throw new Error('请选择图片文件 (jpg, png, gif, etc.)')
    } else if (fileType.value === 'audio' && !file.type.startsWith('audio/')) {
      throw new Error('请选择音频文件 (mp3, wav, etc.)')
    } else if (fileType.value === 'document') {
      const validExtensions = ['.pdf', '.txt', '.docx']
      const fileExtension = file.name.substring(file.name.lastIndexOf('.')).toLowerCase()
      if (!validExtensions.includes(fileExtension)) {
        throw new Error('请选择文档文件 (pdf, txt, docx)')
      }
    }
    
    // Convert file to base64
    const base64Data = await fileToBase64(file)
    
    // Emit the file data to parent component
    emit('file-selected', {
      name: file.name,
      type: file.type,
      size: file.size,
      base64: base64Data,
      originalFile: file
    })
    
    // Reset file input to allow selecting the same file again
    event.target.value = ''
  } catch (error) {
    console.error('Error processing file:', error)
    errorMessage.value = `文件处理失败: ${error.message}`
  } finally {
    isLoading.value = false
  }
}

// Convert file to base64
const fileToBase64 = (file) => {
  return new Promise((resolve, reject) => {
    const reader = new FileReader()
    
    reader.onload = () => {
      // Get the base64 string (remove the data URL prefix)
      const base64String = reader.result.split(',')[1]
      resolve(base64String)
    }
    
    reader.onerror = () => {
      reject(new Error('文件读取失败'))
    }
    
    reader.readAsDataURL(file)
  })
}

// Trigger file input click
const openFileSelector = () => {
  fileInput.value.click()
}

// Switch file type
const switchFileType = (type) => {
  fileType.value = type
}
</script>

<template>
  <div class="file-uploader">
    <!-- Hidden file input -->
    <input
      ref="fileInput"
      type="file"
      class="hidden"
      :accept="acceptTypes"
      @change="handleFileSelect"
    />
    
    <!-- File type toggle - 只在非知识库页面显示 -->
    <div v-if="availableFileTypes.length > 1" class="file-type-toggle mb-2 flex rounded-lg overflow-hidden">
      <button
        v-if="availableFileTypes.includes('image')"
        @click="switchFileType('image')"
        class="toggle-button px-3 py-1 text-sm"
        :class="fileType === 'image' ? 'active-toggle' : 'inactive-toggle'"
      >
        <i class="fas fa-image mr-1"></i>
        图片
      </button>
      <button
        v-if="availableFileTypes.includes('audio')"
        @click="switchFileType('audio')"
        class="toggle-button px-3 py-1 text-sm"
        :class="fileType === 'audio' ? 'active-toggle' : 'inactive-toggle'"
      >
        <i class="fas fa-music mr-1"></i>
        音频
      </button>
      <button
        v-if="availableFileTypes.includes('document')"
        @click="switchFileType('document')"
        class="toggle-button px-3 py-1 text-sm"
        :class="fileType === 'document' ? 'active-toggle' : 'inactive-toggle'"
      >
        <i class="fas fa-file-alt mr-1"></i>
        文档
      </button>
    </div>
    
    <!-- Upload button -->
    <button
      @click="openFileSelector"
      class="upload-button flex items-center justify-center px-3 py-2 rounded-lg bg-gradient-to-r from-blue-500 to-indigo-600 text-white hover:from-blue-600 hover:to-indigo-700 transition-all duration-300 shadow-md"
      :class="{ 'opacity-70 cursor-not-allowed': isLoading }"
      :disabled="isLoading"
    >
      <i class="fas fa-upload mr-2"></i>
      <span v-if="isLoading">处理中...</span>
      <span v-else>
        <template v-if="fileType === 'image'">上传图片</template>
        <template v-else-if="fileType === 'audio'">上传音频</template>
        <template v-else-if="fileType === 'document'">上传文档</template>
      </span>
    </button>
    
    <!-- Error message -->
    <div v-if="errorMessage" class="text-red-500 text-sm mt-2">
      {{ errorMessage }}
    </div>
    
    <!-- File type info -->
    <div class="text-xs text-gray-500 mt-2">
      <template v-if="fileType === 'image'">
        支持的格式: JPG, PNG, GIF, WEBP
      </template>
      <template v-else-if="fileType === 'audio'">
        支持的格式: MP3, WAV, OGG, M4A
      </template>
      <template v-else-if="fileType === 'document'">
        支持的格式: PDF, TXT, DOCX
      </template>
    </div>
  </div>
</template>

<style scoped>
.hidden {
  display: none;
}

.upload-button {
  position: relative;
  overflow: hidden;
}

.upload-button:hover {
  transform: translateY(-1px);
}

.upload-button:active {
  transform: translateY(1px);
}

.file-type-toggle {
  border: 1px solid #e2e8f0;
}

.toggle-button {
  transition: all 0.3s ease;
}

.active-toggle {
  background-color: #4f46e5;
  color: white;
  font-weight: 500;
}

.inactive-toggle {
  background-color: #f8fafc;
  color: #64748b;
}
</style> 